package com.fifi.java.lanchain4j.store;

import com.fifi.java.lanchain4j.bean.ChatMessages;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

@Component//不能是new出来的，初始化在上下文？？？？
public class MongoChatMemoryStore implements ChatMemoryStore {

   @Autowired
   private MongoTemplate mongoTemplate;

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);

        //此处的ChatMessage是自己定义的，用来封装聊天记忆的
        ChatMessages chatMessages = mongoTemplate.findOne(query,ChatMessages.class);
        //之前存content，是把conten转换成了json，现在取出，要反向转换
        //如果查找id不存在，会报空指针异常
        if(chatMessages==null){
            return new LinkedList<>();
        }
        String contentJson = chatMessages.getContent();
        return ChatMessageDeserializer.messagesFromJson(contentJson);
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);
        Update update = new Update();
        //但是，list存储在数据库中需要时json格式的字符串，需要进行转化
        update.set("content", ChatMessageSerializer.messagesToJson(list));
        mongoTemplate.upsert(query,update, com.fifi.java.lanchain4j.bean.ChatMessages.class);
    }

    @Override
    public void deleteMessages(Object memoryId) {
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);
        mongoTemplate.remove(query, com.fifi.java.lanchain4j.bean.ChatMessages.class);
    }
}
